package com.ds.infra.rpc.example.consumer.dao;

import com.ds.infra.rpc.example.api.dto.OrderDTO;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

@Repository
public class OrderRepository {

    private final Map<Long, OrderDTO> orderStore = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);

    public OrderDTO save(OrderDTO order) {
        if (order.getId() == null) {
            order.setId(idGenerator.getAndIncrement());
        }
        orderStore.put(order.getId(), order);
        return order;
    }

    public Optional<OrderDTO> findById(Long id) {
        return Optional.ofNullable(orderStore.get(id));
    }

    public List<OrderDTO> findByUserId(Long userId) {
        return orderStore.values().stream()
                .filter(order -> userId.equals(order.getUserId()))
                .collect(Collectors.toList());
    }
}
